<template>
	<div class="oauth-container">
		<div class="spinner">
			<div class="bounce1"></div>
			<div class="bounce2"></div>
			<div class="bounce3"></div>
		</div>
		<div class="error-info" v-if="error_message != null">{{error_message}}, {{seconds}}秒后返回</div>
	</div>
</template>

<script setup>
import {oauth} from "@/api/login";
import {setToken} from '@/utils/auth'
import useUserStore from '@/store/modules/user'

const route = useRoute();
const router = useRouter();
var error_message = ref(null);
var seconds = ref(3);
const redirect = ref(undefined);

watch(route, (newRoute) => {
	redirect.value = newRoute.query && newRoute.query.redirect;
}, {immediate: true});

function setError(s) {
	const userStore = useUserStore();
	userStore.logOut().then(() => {
		location.href = '/index';
	});
	/*error_message.value = s;
	seconds.value = 3;
	setInterval(function() {
		if(seconds.value > 0) {
			seconds.value--;
		}
		if(seconds.value == 0) {
			router.push({path: "/"});
		}
	}, 1000);*/
}

function auth() {
	const url = new URL(window.location.href);
	const params = route.query;
	var client_code = null;
	if('client_code' in params) {
		client_code = params['client_code'];
	}
	else if('code' in params) {
		client_code = params['code'];
	}
	if(typeof client_code !== 'string' || client_code.length === 0) {
		setError('参数非法');
	}
	else {
		oauth({'client_code': client_code}).then(results => {
			if('token' in results) {
				setToken(results.token);
				const query = route.query;
				const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
					if (cur !== "redirect") {
						acc[cur] = query[cur];
					}
					return acc;
				}, {});
				router.push({path: redirect.value || "/", query: otherQueryParams});
			}
			else {
				console.log(results);
				setError('认证失败');
			}
		}).catch(err => {
			console.log(err);
			setError('认证错误');
		});
	}
}

auth();
</script>

<style lang='scss' scoped>
	.oauth-container {
		background-color: rgb(85, 100, 115);
		height: 100%;
		padding-top: 20%;
	}

	.error-info {
		margin-top: 100px;
		color: white;
		font-size: 25px;
		font-weight: bold;
		text-align: center;
	}

	.spinner {
		margin: 0 auto 0 auto;
		width: 70px;
		text-align: center;
	}

	.spinner > div {
		width: 18px;
		height: 18px;
		background-color: white;

		border-radius: 100%;
		display: inline-block;
		-webkit-animation: sk-bouncedelay 1.4s infinite ease-in-out both;
		animation: sk-bouncedelay 1.4s infinite ease-in-out both;
	}

	.spinner .bounce1 {
		-webkit-animation-delay: -0.32s;
		animation-delay: -0.32s;
	}

	.spinner .bounce2 {
		-webkit-animation-delay: -0.16s;
		animation-delay: -0.16s;
	}

	@-webkit-keyframes sk-bouncedelay {
		0%, 80%, 100% { -webkit-transform: scale(0) }
		40% { -webkit-transform: scale(1.0) }
	}

	@keyframes sk-bouncedelay {
		0%, 80%, 100% {
			-webkit-transform: scale(0);
			transform: scale(0);
		} 40% {
			-webkit-transform: scale(1.0);
			transform: scale(1.0);
		}
	}
</style>
